import React, { useState } from 'react';
import { Palette, Search, Filter, Plus, Edit, Trash2, Eye, Download, Upload, MoreVertical, Star, Settings, Copy } from 'lucide-react';
import MenuToggle from '../components/MenuToggle';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';

const ThemeManagement = ({ toggleSidebar }) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedThemes, setSelectedThemes] = useState([]);
  const [filterStatus, setFilterStatus] = useState('all');
  const [showCreateDialog, setShowCreateDialog] = useState(false);

  // 模拟主题数据
  const [themes, setThemes] = useState([
    {
      id: 1,
      name: '默认主题',
      description: '系统默认的蓝色主题，简洁现代',
      status: 'active',
      type: 'system',
      version: 'v1.0',
      author: '系统',
      createTime: '2024-01-15',
      updateTime: '2024-01-20',
      downloadCount: 0,
      rating: 5.0,
      preview: 'https://nocode.meituan.com/photo/search?keyword=blue,theme,ui&width=300&height=200',
      colors: {
        primary: '#2563eb',
        secondary: '#64748b',
        accent: '#f59e0b',
        background: '#ffffff'
      }
    },
    {
      id: 2,
      name: '深色主题',
      description: '护眼的深色主题，适合夜间使用',
      status: 'active',
      type: 'system',
      version: 'v1.2',
      author: '系统',
      createTime: '2024-01-10',
      updateTime: '2024-01-18',
      downloadCount: 156,
      rating: 4.8,
      preview: 'https://nocode.meituan.com/photo/search?keyword=dark,theme,ui&width=300&height=200',
      colors: {
        primary: '#3b82f6',
        secondary: '#6b7280',
        accent: '#f59e0b',
        background: '#1f2937'
      }
    },
    {
      id: 3,
      name: '绿色自然',
      description: '清新的绿色主题，贴近自然',
      status: 'active',
      type: 'custom',
      version: 'v1.0',
      author: '张三',
      createTime: '2024-01-08',
      updateTime: '2024-01-16',
      downloadCount: 89,
      rating: 4.6,
      preview: 'https://nocode.meituan.com/photo/search?keyword=green,nature,theme&width=300&height=200',
      colors: {
        primary: '#10b981',
        secondary: '#6b7280',
        accent: '#f59e0b',
        background: '#ffffff'
      }
    },
    {
      id: 4,
      name: '紫色梦幻',
      description: '优雅的紫色主题，充满科技感',
      status: 'draft',
      type: 'custom',
      version: 'v0.9',
      author: '李四',
      createTime: '2024-01-05',
      updateTime: '2024-01-14',
      downloadCount: 23,
      rating: 4.2,
      preview: 'https://nocode.meituan.com/photo/search?keyword=purple,tech,theme&width=300&height=200',
      colors: {
        primary: '#8b5cf6',
        secondary: '#6b7280',
        accent: '#f59e0b',
        background: '#ffffff'
      }
    },
    {
      id: 5,
      name: '橙色活力',
      description: '充满活力的橙色主题',
      status: 'inactive',
      type: 'custom',
      version: 'v1.1',
      author: '王五',
      createTime: '2024-01-12',
      updateTime: '2024-01-19',
      downloadCount: 67,
      rating: 4.4,
      preview: 'https://nocode.meituan.com/photo/search?keyword=orange,energy,theme&width=300&height=200',
      colors: {
        primary: '#f97316',
        secondary: '#6b7280',
        accent: '#3b82f6',
        background: '#ffffff'
      }
    }
  ]);

  const [newTheme, setNewTheme] = useState({
    name: '',
    description: '',
    type: 'custom',
    colors: {
      primary: '#2563eb',
      secondary: '#64748b',
      accent: '#f59e0b',
      background: '#ffffff'
    }
  });

  // 过滤主题数据
  const filteredThemes = themes.filter(theme => {
    const matchesSearch = theme.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         theme.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         theme.author.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || theme.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  const handleThemeSelect = (themeId) => {
    setSelectedThemes(prev => 
      prev.includes(themeId) 
        ? prev.filter(id => id !== themeId)
        : [...prev, themeId]
    );
  };

  const handleSelectAll = () => {
    if (selectedThemes.length === filteredThemes.length) {
      setSelectedThemes([]);
    } else {
      setSelectedThemes(filteredThemes.map(theme => theme.id));
    }
  };

  const handleCreateTheme = () => {
    const id = Math.max(...themes.map(t => t.id)) + 1;
    const currentTime = new Date().toISOString().split('T')[0];
    
    setThemes(prev => [...prev, {
      ...newTheme,
      id,
      status: 'draft',
      version: 'v1.0',
      author: '当前用户',
      createTime: currentTime,
      updateTime: currentTime,
      downloadCount: 0,
      rating: 0,
      preview: 'https://nocode.meituan.com/photo/search?keyword=theme,ui,design&width=300&height=200'
    }]);
    
    setNewTheme({
      name: '',
      description: '',
      type: 'custom',
      colors: {
        primary: '#2563eb',
        secondary: '#64748b',
        accent: '#f59e0b',
        background: '#ffffff'
      }
    });
    setShowCreateDialog(false);
  };

  const handleDeleteTheme = (themeId) => {
    setThemes(prev => prev.filter(theme => theme.id !== themeId));
    setSelectedThemes(prev => prev.filter(id => id !== themeId));
  };

  const handleApplyTheme = (themeId) => {
    // 这里应该调用API应用主题
    console.log('应用主题:', themeId);
    alert('主题已应用');
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      active: { color: 'bg-green-100 text-green-800', text: '已发布' },
      draft: { color: 'bg-blue-100 text-blue-800', text: '草稿' },
      inactive: { color: 'bg-gray-100 text-gray-800', text: '已停用' }
    };
    
    const config = statusConfig[status] || statusConfig.draft;
    return (
      <Badge className={`${config.color} hover:${config.color}`}>
        {config.text}
      </Badge>
    );
  };

  const getTypeBadge = (type) => {
    return type === 'system' ? (
      <Badge className="bg-purple-100 text-purple-800 hover:bg-purple-100">
        系统
      </Badge>
    ) : (
      <Badge variant="secondary" className="bg-orange-100 text-orange-800 hover:bg-orange-100">
        自定义
      </Badge>
    );
  };

  const activeCount = themes.filter(t => t.status === 'active').length;
  const draftCount = themes.filter(t => t.status === 'draft').length;
  const customCount = themes.filter(t => t.type === 'custom').length;
  const totalDownloads = themes.reduce((sum, theme) => sum + theme.downloadCount, 0);

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <Palette className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    主题管理
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    管理和自定义系统主题
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-material-grey-500" />
                <input
                  type="text"
                  placeholder="搜索主题..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-10 pr-4 py-2 w-80 border border-material-grey-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors"
                />
              </div>

              <Select value={filterStatus} onValueChange={setFilterStatus}>
                <SelectTrigger className="w-32">
                  <Filter className="w-4 h-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">已发布</SelectItem>
                  <SelectItem value="draft">草稿</SelectItem>
                  <SelectItem value="inactive">已停用</SelectItem>
                </SelectContent>
              </Select>

              <Button variant="outline">
                <Upload className="w-4 h-4 mr-2" />
                导入主题
              </Button>

              <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
                <DialogTrigger asChild>
                  <Button className="bg-primary hover:bg-primary-600">
                    <Plus className="w-4 h-4 mr-2" />
                    新建主题
                  </Button>
                </DialogTrigger>
                <DialogContent className="sm:max-w-lg">
                  <DialogHeader>
                    <DialogTitle>新建主题</DialogTitle>
                  </DialogHeader>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="name">主题名称</Label>
                      <Input
                        id="name"
                        value={newTheme.name}
                        onChange={(e) => setNewTheme(prev => ({ ...prev, name: e.target.value }))}
                        placeholder="请输入主题名称"
                      />
                    </div>
                    <div>
                      <Label htmlFor="description">主题描述</Label>
                      <Textarea
                        id="description"
                        value={newTheme.description}
                        onChange={(e) => setNewTheme(prev => ({ ...prev, description: e.target.value }))}
                        placeholder="请输入主题描述"
                        rows={3}
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="primary">主色调</Label>
                        <div className="flex items-center space-x-2">
                          <Input
                            id="primary"
                            type="color"
                            value={newTheme.colors.primary}
                            onChange={(e) => setNewTheme(prev => ({ 
                              ...prev, 
                              colors: { ...prev.colors, primary: e.target.value }
                            }))}
                            className="w-12 h-10 p-1 border rounded"
                          />
                          <Input
                            value={newTheme.colors.primary}
                            onChange={(e) => setNewTheme(prev => ({ 
                              ...prev, 
                              colors: { ...prev.colors, primary: e.target.value }
                            }))}
                            placeholder="#2563eb"
                            className="flex-1"
                          />
                        </div>
                      </div>
                      <div>
                        <Label htmlFor="secondary">辅助色</Label>
                        <div className="flex items-center space-x-2">
                          <Input
                            id="secondary"
                            type="color"
                            value={newTheme.colors.secondary}
                            onChange={(e) => setNewTheme(prev => ({ 
                              ...prev, 
                              colors: { ...prev.colors, secondary: e.target.value }
                            }))}
                            className="w-12 h-10 p-1 border rounded"
                          />
                          <Input
                            value={newTheme.colors.secondary}
                            onChange={(e) => setNewTheme(prev => ({ 
                              ...prev, 
                              colors: { ...prev.colors, secondary: e.target.value }
                            }))}
                            placeholder="#64748b"
                            className="flex-1"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setShowCreateDialog(false)}>
                      取消
                    </Button>
                    <Button onClick={handleCreateTheme}>
                      创建主题
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        {/* 统计卡片 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总主题数</p>
                  <p className="text-2xl font-bold text-material-grey-900">{themes.length}</p>
                </div>
                <div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                  <Palette className="w-6 h-6 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">已发布</p>
                  <p className="text-2xl font-bold text-green-600">{activeCount}</p>
                </div>
                <div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                  <Eye className="w-6 h-6 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">自定义主题</p>
                  <p className="text-2xl font-bold text-blue-600">{customCount}</p>
                </div>
                <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                  <Settings className="w-6 h-6 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-material-grey-600">总下载量</p>
                  <p className="text-2xl font-bold text-orange-600">{totalDownloads}</p>
                </div>
                <div className="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                  <Download className="w-6 h-6 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 主题网格 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredThemes.map((theme) => (
            <Card key={theme.id} className="group hover:shadow-lg transition-shadow duration-200">
              <CardContent className="p-0">
                {/* 主题预览图 */}
                <div className="relative">
                  <img
                    src={theme.preview}
                    alt={theme.name}
                    className="w-full h-40 object-cover rounded-t-lg mx-auto"
                  />
                  <div className="absolute top-2 right-2 flex space-x-1">
                    {getTypeBadge(theme.type)}
                  </div>
                  <div className="absolute bottom-2 left-2">
                    {getStatusBadge(theme.status)}
                  </div>
                </div>

                {/* 主题信息 */}
                <div className="p-4">
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex-1">
                      <h3 className="font-semibold text-material-grey-900 truncate">{theme.name}</h3>
                      <p className="text-sm text-material-grey-600 line-clamp-2">{theme.description}</p>
                    </div>
                    <div className="ml-2">
                      <input
                        type="checkbox"
                        checked={selectedThemes.includes(theme.id)}
                        onChange={() => handleThemeSelect(theme.id)}
                        className="w-4 h-4 text-primary border-material-grey-300 rounded focus:ring-primary/50"
                      />
                    </div>
                  </div>

                  {/* 颜色预览 */}
                  <div className="flex items-center space-x-2 mb-3">
                    <span className="text-xs text-material-grey-500">配色：</span>
                    <div className="flex space-x-1">
                      <div 
                        className="w-4 h-4 rounded-full border border-material-grey-300"
                        style={{ backgroundColor: theme.colors.primary }}
                      ></div>
                      <div 
                        className="w-4 h-4 rounded-full border border-material-grey-300"
                        style={{ backgroundColor: theme.colors.secondary }}
                      ></div>
                      <div 
                        className="w-4 h-4 rounded-full border border-material-grey-300"
                        style={{ backgroundColor: theme.colors.accent }}
                      ></div>
                    </div>
                  </div>

                  {/* 主题统计 */}
                  <div className="flex items-center justify-between text-xs text-material-grey-500 mb-3">
                    <div className="flex items-center space-x-3">
                      <span className="flex items-center">
                        <Download className="w-3 h-3 mr-1" />
                        {theme.downloadCount}
                      </span>
                      <span className="flex items-center">
                        <Star className="w-3 h-3 mr-1" />
                        {theme.rating}
                      </span>
                    </div>
                    <span>by {theme.author}</span>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex items-center space-x-2">
                    <Button
                      size="sm"
                      onClick={() => handleApplyTheme(theme.id)}
                      className="flex-1 bg-primary hover:bg-primary-600"
                    >
                      应用主题
                    </Button>
                    <Button variant="outline" size="sm">
                      <Eye className="w-4 h-4" />
                    </Button>
                    <Button variant="outline" size="sm">
                      <MoreVertical className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* 空状态 */}
        {filteredThemes.length === 0 && (
          <div className="text-center py-12">
            <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
              <Palette className="w-8 h-8 text-material-grey-500" />
            </div>
            <h3 className="text-lg font-medium text-material-grey-700 mb-2">
              {searchQuery ? '未找到匹配的主题' : '暂无主题'}
            </h3>
            <p className="text-material-grey-500">
              {searchQuery ? '尝试使用不同的关键词搜索' : '点击上方按钮开始创建主题'}
            </p>
          </div>
        )}
      </div>
    </>
  );
};

export default ThemeManagement;
